package com.dushibao.service.impl;

import com.dushibao.dao.UserDao;
import com.dushibao.entity.User;
import com.dushibao.service.UserService;
import com.dushibao.util.Page;
import com.dushibao.util.ResultUtils;
import com.dushibao.util.SecurityHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class UserServiceImpl implements UserService {
    UserDao userDao = new UserDao();

    @Override
    public String login() {
        HttpServletRequest req = SecurityHolder.request.get();

        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        List<User> users = userDao.queryByUserNameAndPassword(userName,password);

        if(users.size()==1){
            Map<String,Object> rets = new HashMap<>();
            rets.put("token", UUID.randomUUID().toString());
            return ResultUtils.success(rets);
        }

        return ResultUtils.error("未找到");
    }

    @Override
    public String page() {
        HttpServletRequest req = SecurityHolder.request.get();

        String current = req.getParameter("current");
        String pageSize = req.getParameter("pageSize");
        String userName = req.getParameter("userName");
        Page iPage = new Page();
        iPage.setCurrent(Integer.parseInt(current==null?"1":current));
        iPage.setPageSize(Integer.parseInt(pageSize==null?"10":pageSize));

        iPage = this.userDao.page(iPage,userName);

        Map<String,Object> maps = new HashMap<>();
        maps.put("iPage",iPage);
        maps.put("userName",userName);

        return ResultUtils.success(maps);
    }

    @Override
    public User getById(long id) {
        return userDao.getById(id);
    }


    @Override
    public Integer saveOrUpdate(User user) {
        if(user.getId()!=null){
            return userDao.update(user);
        }
        return userDao.save(user);
    }

    @Override
    public Integer deleteById(List<Long> ids) {
        return userDao.deleteById(ids);
    }

    @Override
    public Integer save(User user) {
        List<User> users = userDao.queryByUserName(user.getUserName());
        if(users.size()>0){
            return 1;
        }
        return userDao.save(user);
    }

    @Override
    public List<User> queryByUserNameAndPassword(String userName, String password) {
        return userDao.queryByUserNameAndPassword(userName,password);
    }

    @Override
    public Integer update(User user) {
        return userDao.update(user);
    }

    @Override
    public List<User> list(List<Long> userIds) {
        return userDao.list(userIds);
    }

    @Override
    public boolean saveBatch(List<User> users) {

        return userDao.saveBatch(users);
    }
}
